#include <iostream>
#include <curl/curl.h>
#include <map>
#include <regex>
#include <vector>
#include <filesystem>

using namespace std;
namespace fs = std::filesystem;

const static string URL = "http://127.0.0.1:9999";
const static string PATH = "./image";

size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
    size_t totalSize = size * nmemb;
    output->append((char*)contents, totalSize);
    return totalSize;
}

string request_get(const string& url, map<string, string> headers = map<string, string>()) {
    CURL* curl;
    CURLcode statusCode;
    string htmlData;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &htmlData);
        
        auto res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        }

        curl_easy_cleanup(curl);
    } else {
        std::cerr << "curl_easy_init() failed." << std::endl;
        return ""; // Return empty string if curl init failed
    }

    curl_global_cleanup();
    return htmlData;
}

vector<string> getImgUrls(const string& html) {
    regex reg("/img/\\w+\\.(jpg|png)");
    smatch result;
    vector<string> imgUrls;
    for (sregex_iterator it(html.begin(), html.end(), reg), end_it; it != end_it; ++it) {
        imgUrls.push_back(it->str());
    }
    return imgUrls;
}

int main() {
    if (!fs::exists(PATH)) {
        fs::create_directories(PATH);
    }

    map<string, string> headers;
    headers["cookies"] = "PHPAESSID=91qt15n0tr35dan15708idk8ar";
    
    string html = request_get(URL, headers);
    
    vector<string> imgUrls = getImgUrls(html);
    
    for (const auto& imgUrl : imgUrls) {
        cout << imgUrl << endl;
        
        string url = URL + imgUrl;
        string imageName = PATH + imgUrl.substr(imgUrl.find_last_of("/"));
        
        const char* fileUrl = url.c_str();
        const char* fileName = imageName.c_str();
        
        // Download file function is missing, please implement your download logic here
    }
    
    return 0;
}